package log

import (
	"fmt"
	log "github.com/cihub/seelog"
	"github.com/pkg/errors"
	"os"
	"path/filepath"
	"strings"
)

func init() {
	err := InitLog()
	if err != nil {
		_ = log.Error(printError(err))
	}
}

func Flush() {
	log.Flush()
}

func InitLog() error {
	path := "config/seelog.xml"
	abs, err2 := filepath.Abs(path)
	if err2 != nil {
		return err2
	} else {
		log.Info("日志的配置文件存放在：", abs)
	}
	logger, err := log.LoggerFromConfigAsFile(path)
	if err != nil {
		_ = log.Error("初始化日志环境信息时出现异常。")
		err = errors.WithStack(err)
		return err
	}
	err = log.ReplaceLogger(logger)
	return err
}

func printError(err error) string {
	errMsg := fmt.Sprintf("%+v", err)
	return CleanPath(errMsg)
}

func CleanPath(s string) string {
	return strings.ReplaceAll(s, GetCurrentPath()+"/", "")
}

func Info(message string) {
	log.Info(CleanPath(message))
}

func Infof(format string, params ...interface{}) {
	log.Infof(format, params)
}

func Errorf(format string, params ...interface{}) {
	_ = log.Errorf(format, params)
}

func Error(error error) {
	s := printError(error)
	_ = log.Error(s)
}

func ErrorString(message string) {
	_ = log.Error(message)
}

// 获取当前项目目录
func GetCurrentPath() string {
	getwd, err := os.Getwd()
	if err != nil {
		_ = log.Warn("获取项目运行路径出现异常。")
		return ""
	}
	replace := strings.Replace(getwd, "\\", "/", -1)
	return replace
}
